<?php

namespace app\index\controller;

use app\model\Category;
use app\model\Config;
use app\model\Goods;
use app\model\GoodsAudit;
use app\model\GoodsDescription;
use app\model\GoodsImage;
use app\model\GoodsMemberDiscount;
use app\model\GoodsShareCharges;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\Member;
use app\model\MemberAuthGroup;
use app\model\MemberAutonym;
use app\model\MemberTransfer;
use app\model\Operatingcity;
use app\model\Store;
use think\exception\ValidateException;
use app\model\Users;

class AdminController extends Base
{

	public function detail()
	{
		$user = Users::getadminbyopenid();

		if ($user) {
			$data = $user;
		} else {
			$data = 0;
			$message = '您不是管理员！';
		}

		return $this->json(['message' => $message, 'data' => $data]);
	}
	public function service_audit(){
        $model        = new GoodsAudit();
        $weid         = weid();
        $page         = input('post.page', 1, 'intval');
        $keyword      = input('post.keyword', '', 'serach_in');
        $cat_id       = input('post.cat_id', '', 'serach_in');
        $ptype        = input('post.ptype', '', 'serach_in');
        $is_recommand = input('post.is_recommand', '', 'serach_in');
        $audit_status = input('post.audit_status','','serach_in');
        $where['weid'] = $weid;
        $query = $model->where($where);
        if (!empty($ptype)) {
            $query->where('ptype', $ptype);
        } else {
            $query->where('ptype', '>', 0);
        }
        if (!empty($this->sid)) {
            $query->where('sid', $this->sid);
        }

        if (!empty($keyword)) {
            $query->where('name', 'like', '%' . $keyword . '%');
        }

        if (!empty($cat_id)) {
            $query->where('cat_id',  $cat_id);
        }

        if (!empty($is_recommand) || $is_recommand === "0") {
            $query->where('is_recommand', $is_recommand);
        }

        if($audit_status){
            $query->where('audit_status', $audit_status);
        }

        $res = $query->order('audit_status asc')
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['image'] = toimg($vo['image']);
            if ($vo['sid'] == 0) {
                $vo['name'] = '[自营]' . $vo['name'];
            } else {
                $StoreTitle = Store::getTitle($vo['sid']);
                if (empty($StoreTitle)) {
                    $vo['name'] = '[商户已被删除]' . $vo['name'];
                } else {
                    $vo['name'] = '[' . $StoreTitle . ']' . $vo['name'];
                }
            }
            $vo['cat_id'] = Category::getTitle($vo['cat_id']);
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['update_time'] = time_format($vo['update_time']);
        }
        $data['data'] = $res;
        if ($page == 1) {
            $data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray());
        }
        return $this->json(['message' => 'ok', 'data' => $data]);
    }

    public function serviceInfo()
    {
        $id =  $this->request->post('id');
        $model  = new GoodsAudit();
        if ($id) {
            $data = $model->field('*')->find($id)->toArray();
        } else {
            $data = [
                'is_times' => 0,
                'sort' => 100,
                'status' => 1,
            ];
        }

        return $this->json(['data' => $data]);
    }

    public function service_update()
    {
        $id = request()->post('id');
        $data = input('post.');
        $data['update_time'] = time();
        if(!empty( $data['images'][0]['url'])){
            $data['image'] =  $data['images'][0]['url'];
        }
        $goods_moel  = new GoodsAudit();

        if(empty($data['audit_status'])){
            throw new ValidateException('请选择审核状态');
        }
        $goodsInfo = $goods_moel->where(['id'=>$id,'audit_status'=>1])->find();
        if(!$goodsInfo){
            throw new ValidateException('数据不存在或已被审核');
        }
        $goodsInfo->audit_time   = time();
        $goodsInfo->audit_status = $data['audit_status'];
        if($data['audit_status'] == 3){
            if(empty($data['reason'])){
                throw new ValidateException('请填写驳回原因');
            }
            try {
                $goodsInfo->reason       = $data['reason'];
                $goodsInfo->audit_time   = time();
                $goodsInfo->save();
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '操作成功']);
        }

        if (!empty($data['cat_id'])) {
            $cat = Category::find($data['cat_id']);
            if (!empty($cat)) {
                $cat = $cat->toArray();
            }
            $data['ptype'] = $cat['ptype'];
            $data['deliverymode'] = $cat['deliverymode'];
        }
        if (!empty($data['videourl'])) {
            $data['videotype'] = 1;
        } elseif (!empty($data['videoid'])) {
            $data['videotype'] = 2;
        } else {
            $data['videotype'] = 0;
        }


        $data['weid'] = weid();
        $data['create_time'] = time();

        if (!empty($this->sid)) {
            $data['sid'] = $this->sid;

            $storemod = Store::find($this->sid);
            if ($storemod) {
                $data['province_name'] = $storemod->province_name;
                $data['city_name'] = $storemod->city_name;
                $data['district_name'] = $storemod->district_name;
            }
        }
        $data['ocid'] = $goodsInfo['ocid'];
        $ocmod = Operatingcity::find($data['ocid']);
        if ($ocmod) {
            $data['province_name'] = $ocmod->province_name;
            $data['city_name'] = $ocmod->city_name;
            $data['district_name'] = $ocmod->district_name;
        }
        if (empty($data['tel'])) {
            $data['tel'] = '';
        }
        try {
            if(empty($goodsInfo['goods_id'])){
                unset($data['id']);
                $res = Goods::create($data);
                if ($res->id && empty($data['sort'])) {
                    Goods::update(['sort' => $res->id, 'id' => $res->id]);
                }
                $goodsInfo->goods_id = $res->id;
            }else{
                $data['id'] = $goodsInfo['goods_id'];
                unset($data['audit_status'],$data['reason']);
                Goods::update($data);
                $goodsInfo->goods_id = $data['id'];
            }
            $goodsInfo->reason   = '';
            $goodsInfo->save();
            $data['id'] = $res->id;
            $this->_synupdata($data);
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '操作成功', 'data' => $res->id]);
    }

    function _synupdata($data)
    {
        //详情
        if (empty(GoodsDescription::where('goods_id', $data['id'])->find())) {
            GoodsDescription::create([
                'goods_id' => (int) $data['id'],
                'description' => $data['description']
            ]);
        } else {
            GoodsDescription::where('goods_id', $data['id'])->update(['description' => $data['description']]);
        }

        //sku

        GoodsSku::where('goods_id', $data['id'])->delete();
        if (isset($data['attribute'])) {
            foreach ($data['attribute'] as $attr) {
                GoodsSku::create([
                    'goods_id' => (int) $data['id'],
                    'name' => $attr['name'],
                    'ptype' => 'radio',
                    'item' =>  implode(',', $attr['item'])
                ]);
            }
        }

        GoodsSkuValue::where('goods_id', $data['id'])->delete();
        if (isset($data['sku'])) {
            foreach ($data['sku'] as $skuarr) {
                GoodsSkuValue::create([
                    'goods_id' => (int) $data['id'],
                    'sku' => $skuarr['sku'],
                    'image' => $skuarr['image'],
                    'quantity' => $skuarr['quantity'],
                    'price' => $skuarr['price']
                ]);
            }
        }

        GoodsShareCharges::where('goods_id', $data['id'])->delete();
        if (!empty($data['is_share_charges']) && !empty($data['sharecharges'])) {
            foreach ($data['sharecharges'] as $scvo) {
                if ($scvo['price'] > 0) {
                    GoodsShareCharges::create([
                        'goods_id' => (int) $data['id'],
                        'level' => $scvo['level'],
                        'price' => (float) $scvo['price'],
                        'charges_method' => (int) $data['charges_method']
                    ]);
                }
            }
        }

        GoodsMemberDiscount::where('goods_id', $data['id'])->delete();
        if (!empty($data['is_member_discount']) && !empty($data['MemberGroup'])) {
            foreach ($data['MemberGroup'] as $mgvo) {
                if ($mgvo['price'] > 0) {
                    GoodsMemberDiscount::create([
                        'goods_id' => (int) $data['id'],
                        'mgid' => (int) $mgvo['id'],
                        'price' => (float) $mgvo['price']
                    ]);
                }
            }
        }
        //图片
        GoodsImage::where('goods_id', $data['id'])->delete();
        if (isset($data['images'])) {
            foreach ($data['images'] as $image) {
                GoodsImage::create([
                    'goods_id' => (int) $data['id'],
                    'weid' => weid(),
                    'image' => $image['url']
                ]);
            }
        }
    }


    //供需列表
  public function gongxuindex()
    {
        $weid = weid();
        $keyword = trim(input('post.keyword', '', 'serach_in'));
        $status  = input('post.status', '', 'serach_in');
        $publish_type = input('post.publish_type');
        $model = new MemberTransfer();
        $query   = $model->where(['weid'=>$weid]);
        if (!empty($keyword)) {
            $query = $query->where('name|buy_demand', 'like', '%' . $keyword . '%');
        }
        if($publish_type){
            $query =  $query->where('publish_type',$publish_type);
        }
        if($status){
            if($status == -1){
                $status = 0;
            }
            $query = $query->where(['status'=>$status]);
        }
        $res = $query->with(['member'])->order('id desc')
            ->paginate(getpage())
            ->toArray();
        $data['data'] = $res;
        return $this->json($data);
    }



    public function gongxuaudit(){
        $id = $this->request->post('id');
        if (!$id) throw new ValidateException('参数错误');
        $model = new MemberTransfer();
        $info = $model->where(['id'=>$id])->find();
        if(!$info){
            throw new ValidateException('数据不存在');
        }
        if($info['status'] != 0){
            throw new ValidateException('数据已经被审核');
        }
        $status = input('status');
        $reason = input('reason');
        if($status == 3 && !$reason){
            throw new ValidateException('驳回审核需填写驳回原因');
        }
        try {
            $info->status = $status;
            if($status == 2){
                $info->reason = $reason;
            }
            $info->audit_time  = time();
            $info->update_time = time();
            $info->save();
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '操作成功']);
    }

    public function gongxuInfo(){
        $model = new MemberTransfer();
        $id =  $this->request->post('id');
        $infodata = $model->where(['id'=>$id])->find();
        return $this->json(['data' => $infodata]);
    }

    //会员审核列表

    function user_audit_index()
    {
        $weid = weid();
        $model = new MemberAutonym();
        $keyword = trim(input('post.keyword', '', 'serach_in'));
        $status = input('post.status', '', 'serach_in');
        $query = $model->where(['weid'=>$weid]);
        if (!empty($keyword)) {
            $query = $query->where('name|mobile', 'like', '%' . $keyword . '%');
        }
        if(!empty($status)){
            $query = $query->where(['status'=>$status]);
        }
        $res = $query->with(['member'])->order('id desc')
            ->paginate(getpage())
            ->toArray();
        $data['data'] = $res;

        return $this->json($data);
    }
    //会员审核详情
    public 	function user_audit_getInfo()
    {
        $id =  $this->request->post('id', '', 'serach_in');
        $infodata = MemberAutonym::where(['id'=>$id])->find();
        return $this->json(['data' => $infodata]);
    }
    //会员审核编辑
    public function user_audit_update()
    {
        $id = $this->request->post('id');
        if (!$id) throw new ValidateException('参数错误');
        $info = MemberAutonym::where(['id'=>$id])->find();
        if(!$info){
            throw new ValidateException('数据不存在');
        }
        if($info['status'] != 1){
            throw new ValidateException('数据已经被审核');
        }
        $status = input('status');
        $reason = input('reason');
        if($status == 3 && !$reason){
            throw new ValidateException('驳回审核需填写驳回原因');
        }
        try {
            $info->status = $status;
            if($status == 3){
                $info->reason = $reason;
            }
            $info->audit_time  = time();
            $info->update_time = time();
            $r = $info->save();
            if($status ==2 && $r){
                Member::where(['id'=>$info->uid])->update(['is_autonym'=>2]);
            }
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '操作成功']);
    }

    public function store_index_audit(){
        $query = new Store();
        $weid = weid();
//        $keyword = trim(input('post.keyword', '', 'serach_in'));
        $status = input('post.status', '', 'serach_in');
//        $query = $model->where(['weid'=>$weid]);
//        if (!empty($keyword)) {
//            $query = $query->where('name|mobile', 'like', '%' . $keyword . '%');
//        }
        $query = $query->where(['weid'=>$weid]);
        if(isset($status)){
            $query = $query->where(['status'=>$status]);
        }
        $res = $query->order('id desc')
            ->paginate(getpage())
            ->toArray();
        $data['data'] = $res;

        return $this->json($data);
    }
    public 	function store_audit_getInfo()
    {
        $id =  $this->request->post('id', '', 'serach_in');
        $infodata = Store::where(['id'=>$id])->find();
        $infodata['username'] = Users::where(['sid'=>$infodata['id']])->value('username');
        return $this->json(['data' => $infodata]);
    }
    public function store_audit_update()
    {
        $id = $this->request->post('id');
        if (!$id) throw new ValidateException('参数错误');
        $info = Store::where(['id'=>$id])->find();
        if(!$info){
            throw new ValidateException('数据不存在');
        }
        $status = input('status');
        try {
            $info->status      = $status;
            $info->update_time = time();
            $info->save();
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return $this->json(['msg' => '操作成功']);
    }
}
